package com.zzyl.nursing.service.impl;

import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.AlertWebSocketService;
import com.zzyl.nursing.websocket.AlertMessage;
import com.zzyl.nursing.websocket.AlertWebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * WebSocket报警推送服务实现类
 * 
 * @author zzyl
 * @date 2025-07-25
 */
@Service
@Slf4j
public class AlertWebSocketServiceImpl implements AlertWebSocketService {

    @Override
    public void sendAlertToUser(String userId, AlertData alertData) {
        if (userId == null || alertData == null) {
            log.warn("用户ID或报警数据为空，跳过推送");
            return;
        }

        try {
            AlertMessage alertMessage = convertToAlertMessage(alertData);
            alertMessage.setIsAllConsumer(false);
            alertMessage.setUserId(Long.parseLong(userId));
            
            AlertWebSocketServer.sendAlertToUser(userId, alertMessage);
            log.info("成功向用户 {} 推送报警消息", userId);
        } catch (Exception e) {
            log.error("向用户 {} 推送报警消息失败", userId, e);
        }
    }

    @Override
    public void sendAlertToUsers(List<String> userIds, AlertData alertData) {
        if (userIds == null || userIds.isEmpty() || alertData == null) {
            log.warn("用户列表为空或报警数据为空，跳过推送");
            return;
        }

        AlertMessage alertMessage = convertToAlertMessage(alertData);
        alertMessage.setIsAllConsumer(false);

        userIds.forEach(userId -> {
            try {
                AlertMessage userSpecificMessage = AlertMessage.builder()
                        .notifyType(alertMessage.getNotifyType())
                        .isAllConsumer(false)
                        .physicalLocationType(alertMessage.getPhysicalLocationType())
                        .deviceDescription(alertMessage.getDeviceDescription())
                        .accessLocation(alertMessage.getAccessLocation())
                        .productName(alertMessage.getProductName())
                        .functionName(alertMessage.getFunctionName())
                        .dataValue(alertMessage.getDataValue())
                        .iotId(alertMessage.getIotId())
                        .deviceName(alertMessage.getDeviceName())
                        .productKey(alertMessage.getProductKey())
                        .alertRuleId(alertMessage.getAlertRuleId())
                        .alertReason(alertMessage.getAlertReason())
                        .alertLevel(alertMessage.getAlertLevel())
                        .userId(Long.parseLong(userId))
                        .createTime(alertMessage.getCreateTime())
                        .alertId(alertMessage.getAlertId())
                        .build();

                AlertWebSocketServer.sendAlertToUser(userId, userSpecificMessage);
                log.info("成功向用户 {} 推送报警消息", userId);
            } catch (Exception e) {
                log.error("向用户 {} 推送报警消息失败", userId, e);
            }
        });

        log.info("批量推送报警消息完成，目标用户数: {}", userIds.size());
    }

    @Override
    public void broadcastAlert(AlertData alertData) {
        if (alertData == null) {
            log.warn("报警数据为空，跳过广播");
            return;
        }

        try {
            AlertMessage alertMessage = convertToAlertMessage(alertData);
            alertMessage.setIsAllConsumer(true);
            
            AlertWebSocketServer.broadcastAlert(alertMessage);
            log.info("成功广播报警消息给所有在线用户");
        } catch (Exception e) {
            log.error("广播报警消息失败", e);
        }
    }

    @Override
    public void sendDeviceAlert(DeviceData deviceData, Integer alertLevel) {
        if (deviceData == null) {
            log.warn("设备数据为空，跳过推送");
            return;
        }

        try {
            AlertMessage alertMessage = AlertMessage.builder()
                    .notifyType(1)  // 报警异常
                    .isAllConsumer(false)
                    .physicalLocationType(deviceData.getPhysicalLocationType())
                    .deviceDescription(deviceData.getDeviceDescription())
                    .accessLocation(deviceData.getAccessLocation())
                    .productName(deviceData.getProductName())
                    .functionName(deviceData.getFunctionId())
                    .dataValue(deviceData.getDataValue())
                    .iotId(deviceData.getIotId())
                    .deviceName(deviceData.getDeviceName())
                    .productKey(deviceData.getProductKey())
                    .alertLevel(alertLevel != null ? alertLevel : 2) // 默认中等级别
                    .createTime(LocalDateTime.now())
                    .build();

            // 根据报警等级决定推送策略
            if (alertLevel != null && alertLevel >= 4) {
                // 紧急报警，广播给所有用户
                alertMessage.setIsAllConsumer(true);
                AlertWebSocketServer.broadcastAlert(alertMessage);
                log.info("紧急设备报警，已广播给所有用户");
            } else {
                // 普通报警，可以根据设备位置推送给相关负责人
                // 这里暂时广播，实际可以根据业务需求调整
                AlertWebSocketServer.broadcastAlert(alertMessage);
                log.info("设备报警，已推送给相关用户");
            }
        } catch (Exception e) {
            log.error("推送设备报警失败", e);
        }
    }

    @Override
    public void sendResolveAlert(String deviceDescription, Integer locationType) {
        if (deviceDescription == null) {
            log.warn("设备描述为空，跳过推送解除报警");
            return;
        }

        try {
            AlertMessage resolveMessage = AlertMessage.builder()
                    .notifyType(0)  // 解除报警
                    .isAllConsumer(false)
                    .physicalLocationType(locationType)
                    .deviceDescription(deviceDescription)
                    .createTime(LocalDateTime.now())
                    .build();

            AlertWebSocketServer.broadcastAlert(resolveMessage);
            log.info("成功推送解除报警消息");
        } catch (Exception e) {
            log.error("推送解除报警消息失败", e);
        }
    }

    @Override
    public boolean isUserOnline(String userId) {
        return AlertWebSocketServer.isUserOnline(userId);
    }

    @Override
    public int getOnlineUserCount() {
        return AlertWebSocketServer.getOnlineUsers().size();
    }

    /**
     * 将AlertData转换为AlertMessage
     */
    private AlertMessage convertToAlertMessage(AlertData alertData) {
        return AlertMessage.builder()
                .notifyType(1)  // 报警异常
                .isAllConsumer(false)
                .physicalLocationType(alertData.getPhysicalLocationType())
                .deviceDescription(alertData.getDeviceDescription())
                .accessLocation(alertData.getAccessLocation())
                .productName(alertData.getProductName())
                .functionName(alertData.getFunctionId())
                .dataValue(alertData.getDataValue())
                .iotId(alertData.getIotId())
                .deviceName(alertData.getDeviceName())
                .productKey(alertData.getProductKey())
                .alertRuleId(alertData.getAlertRuleId())
                .alertReason(alertData.getAlertReason())
                .alertLevel(2) // 默认中等级别，可以根据报警规则配置
                .userId(alertData.getUserId())
                .createTime(LocalDateTime.now())
                .alertId(alertData.getId())
                .build();
    }
} 